package com.gq.rising.common;

import com.gq.rising.util.DbUtils;
import com.gq.rising.util.ValidUtils;
import com.zaxxer.hikari.HikariDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;

/**
 * @Description: 创建按钮布局
 * @Author: GQ
 */
public class ButtonCreate extends JButton {

    // 按钮名字
    private String text;
    // x坐标
    private int x;
    // y坐标
    private int y;
    // 宽
    private int width;
    // 高
    private int height;

    private DbUtils dbUtils = new DbUtils();

    private ValidUtils validUtils = new ValidUtils();

    public static DbSource dbSource;

    public static HikariDataSource hikariDataSource;

    public static DbSource getDbSource() {
        return dbSource;
    }

    public static void setDbSource(DbSource dbSource) {
        ButtonCreate.dbSource = dbSource;
    }

    public static HikariDataSource getHikariDataSource() {
        return hikariDataSource;
    }

    public static void setHikariDataSource(HikariDataSource hikariDataSource) {
        ButtonCreate.hikariDataSource = hikariDataSource;
    }

    public ButtonCreate() {

    }
    private static final Logger logger = LoggerFactory.getLogger(ButtonCreate.class);


    public ButtonCreate(String text, int x, int y, int width, int height) {
        super.setText(text);
        super.setBounds(x, y, width, height);
    }

    // 关闭页面监听事件
    public void exit(){
        super.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(1);
            }
        });
    }

    // 软件信息弹窗
    public void popupAbout(){
        super.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(null, Cons.ABOUT,
                        "About",JOptionPane.INFORMATION_MESSAGE);
            }
        });
    }

    // 测试数据库连接
    public void connection(DbSource dataSource, Map<String, Object> inputBoxValue){
        super.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (dataSource.getName()==null){
                    JOptionPane.showMessageDialog(null, "请选择数据库！",
                            "Please Select A Database",JOptionPane.WARNING_MESSAGE);
                }else{
                    Connection connection = null;
                    try {
                        validUtils.checkInParam(inputBoxValue);
                        DbSource dbSource = dbUtils.buildDataSource(dataSource, inputBoxValue);
                        logger.info("数据源：{}", dbSource);
                        //得到HikariDataSource
                        HikariDataSource hikariDataSource = dbUtils.getHikariDataSource(dbSource);
                        ButtonCreate.this.hikariDataSource = hikariDataSource;
                        //获取连接
                        connection = dbUtils.getConnection(dbSource);
                        if (connection != null){
                            //连接成功标志置1
                            dbSource.setConnectSuccessFlag(1);
                            //让当前类的静态变量dbSource指向单例DbSource
                            ButtonCreate.this.dbSource = dbSource;

                            JOptionPane.showMessageDialog(null, "数据库连接成功！",
                                    "Database connection successful",JOptionPane.INFORMATION_MESSAGE);
                        }
                    } catch (Exception ex) {
                        logger.error("【数据库连接】测试失败，原因：{}", ex.getMessage());
                        JOptionPane.showMessageDialog(null, "数据库连接失败,原因："+ex.getMessage(),
                                "Database connection failed",JOptionPane.WARNING_MESSAGE);
                        ex.printStackTrace();
                    }finally {
                        try {
                            connection.close();
                        } catch (SQLException ex) {
                            ex.printStackTrace();
                        }
                    }

                }
            }
        });
    }

    // 生成数据库表结构文档
    public void invoke(Map<String, Object> inputBoxValue){
        super.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    if(dbSource == null || dbSource.getConnectSuccessFlag() == 0){
                        //未成功连接过，提示先测试连接
                        JOptionPane.showMessageDialog(null, "请先测试数据库连接!",
                                "Please Test Connection First",JOptionPane.WARNING_MESSAGE);
                        return;
                    }else{
                        validUtils.checkInParam(inputBoxValue);
                        //已经连接成功过，直接生成文档
                        GenerateDocument.contextLoads(hikariDataSource);//执行
                        //生成文档后将成功连接标志置0
                        dbSource.setConnectSuccessFlag(0);

                        JOptionPane.showMessageDialog(null, "文档生成成功（路径 C:/Rising/）",
                                "SUCCESS",JOptionPane.INFORMATION_MESSAGE);
                        logger.info("数据库表结构生成文档执行完毕！");
                    }
                } catch (Exception ex) {
                    logger.error("【表结构生成文档】执行失败！原因：{}", ex.getMessage());
                    JOptionPane.showMessageDialog(null, "表结构文档生成失败！原因："+ex.getMessage(),
                            "Internal Server Error",JOptionPane.WARNING_MESSAGE);
                    ex.printStackTrace();
                }
            }
        });
    }
}
